package com.hd.tag;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;

public class ConstantConvert extends Component {

	// 需要转换的常量类型
	private String type;

	// 常量保存在数据库中的值
	private String value;

	private Map constants = new HashMap();

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getValue() {
		return value;
	}

	public void setValue(String value) {
		this.value = value;
	}

	public Map getConstants() {
		return constants;
	}

	public void setConstants(Map constants) {
		this.constants = constants;
	}

	public ConstantConvert(ValueStack stack) {
		super(stack);
	}

	@Override
	public boolean start(Writer writer) {
		boolean result = super.start(writer);

		boolean isValid = true;

		type = type;
		value = parse(value);

		return result;
	}

	private String parse(String value) {

		String actualValue = null;

		if (value == null) {
			value = "top";
		}

		if (altSyntax()) {
			if (value.startsWith("%{") && value.endsWith("}")) {
				value = value.substring(2, value.length() - 1);
			}
		}

		actualValue = (String) getStack().findValue(value, String.class);
		if(actualValue == null) {
			actualValue = value;
		}
		return actualValue;
	}
	
	@Override
	public boolean end(Writer writer, String body) {
		try {
			boolean isValid = true;
			StringBuilder outputStringBuilder = new StringBuilder();

			if (isValid) {
				outputStringBuilder.append(constants.get(type + value));

			}

			writer.write(outputStringBuilder.toString());
		} catch (IOException e) {
			Logger.getLogger(ConstantConvert.class.getName()).log(Level.SEVERE, null, e);
		}

		return super.end(writer, body);
	}

}
